<!--
 * new page
 * @author: YK
 * @since: 2023-11-30
 * index.vue
-->
<template>
  <div class="container">
    <el-select clearable v-model="province" placeholder="请选择省份">
      <el-option
        v-for="item in areas"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      clearable
      :disabled="!province"
      style="margin: 0 10px"
      v-model="city"
      placeholder="请选择城市"
    >
      <el-option
        v-for="item in selectCity"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      clearable
      :disabled="!province || !city"
      v-model="area"
      placeholder="请选择区域"
    >
      <el-option
        v-for="item in selectArea"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup lang="ts">
import { ref, Ref, computed, watch } from "vue";
import allAreas from "../lib/pca-code";
export type areasType = {
  name: string;
  code: string;
  children?: Array<areasType>;
};
export interface Data {
  name: string;
  code: string;
}
const province = ref<string>("");
const city = ref<string>("");
const area = ref<string>("");
//省份数据
const areas: Ref<areasType[]> = ref(allAreas as areasType[]);
//城市数据
const selectCity: Ref<areasType[]> = computed(() => {
  if (province.value) {
    return (
      areas.value.find((item) => item.code === province.value)?.children || []
    );
  }
  return [];
});
//区域数据
const selectArea: Ref<areasType[]> = computed(() => {
  if (city.value && province.value) {
    return (
      selectCity.value.find((item) => item.code === city.value)?.children || []
    );
  }
  return [];
});

watch(
  () => province.value,
  () => {
    area.value = "";
    city.value = "";
  }
);
watch(
  () => city.value,
  () => {
    area.value = "";
  }
);
//分发事件
const emits=defineEmits(['change'])
watch(
  () => area.value,
  (val) => {
    if (!val) return;
    let provinceData: Data = {
      name: areas.value.find((item) => item.code === province.value)!.name,
      code: province.value,
    };
    let cityData: Data = {
      name: selectCity.value.find((item) => item.code === city.value)!.name,
      code: city.value,
    };
    let areaData: Data = {
      name: selectArea.value.find((item) => item.code === area.value)!.name,
      code: area.value,
    };
    emits("change",{province:provinceData,city:cityData,area:areaData})
  }
);
</script>

<style scoped lang="scss"></style>
